package org.zk.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.zk.entity.User;
import org.zk.service.PurseService;
import org.zk.service.UserService;
import org.zk.util.OrderCodeFactory;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
 * @Description TODO
 * @Author 李帅
 * @Date 2020/1/11 0011 上午 10:13
 * @Version 1.0
 **/
@Controller
public class ALiPayController {

    private final String APP_ID = "2016101700709555";
    private final String APP_PRIVATE_KEY = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCkRoh3fJC5BGSlaVTcRfEJaVboOxd75dvbFD6m2WSeEuJQNWO1jIYxF9LN5Jw+EBzkaRKEO6CWZfWcIlMLHCJeA+CmUH0FFpPoFI0m0U50yncyAGpz7EkkIpuXjd2CwmUwc+Ih8jDwk5q9/IrnpVyqUMvXCcOn3NclN75Yj6MCkbUZtH13lekLR2GQFhTAjeR0T5cM7U8VJ9IakJ3VZcAc7hBV6A4o6BUZhJUNUjE6V5z+UBVI/6A+2wHE5HeT3pxEaCI8r/AoE/lLnc47ncb4UGXYhgHaGUybd5c3jMwjW1r4lF2YHCST6tBVShytCjgbHVjrsfQWTBUc+iiDSoybAgMBAAECggEAFKJncdrLsvHCUqSwbBq89BmvOOxzPrTYsOQSGpMj+FcW5kxOgfdsw63iZMpaddFAT9CC6ukyerHD8CC/nZ2jE3wZM8rYaVM0sOoj8MRJvpHP9w/mTzlW1psiQB8pu8r/Ot7TgMATNaTUwxh9uisjQKF1eUVYtjUfMSWXWzhvmVrQgFcdfHCDAy5ssto4QWGvoHX9LSg1DpEDiYXczpD1EldJ3oeFokYP6Fr4T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IBCgKCAQEAmygdHNJbI9YqB2i/ApEJ9u8lqJMSeTSvk7Xiut/QgK/Gb0OsIIFW7JU2M4MP9QIE6tHAM8MKpFGnMLYMXppjeysnNUgO9uwCVf7I2m/hyEpIlp0dgN/wtW6q0RzA33eyUcXiTRSSz5lJUsepklduo1SvbhEPYtWsj4DINXtkyk5Oc9QfQIvCpUBXuKaBIp3cWFrJfQJ3IZTzybktTYOlgmJVwDjZmvJ2Bs0P0vEWw5N7cvKEC6FEFWhUpQogTwMdUvnCXaP1dXJZPYc3ZnQbRqhzzeZ+xfZc+KEAy0jcmkcr6eJNh+CucnG71oVHPTfuOCMYUDlAl3dAASJTTP9OBwIDAQAB";
    //这是沙箱接口路径,正式路径为https://openapi.alipay.com/gateway.doMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAvcgdR6A20pKm8cm79UnEwkwMByKqecJcva7j3oJC+dxf+HK8KGJBOW8aWu9R0UQolN2MM4nvDiU7PTlFCYgxZtnE2hX1KCkJqq6w0JIy14mt7HOcQVipmQsWEAlDERtKjdLnD7R+MKzUYMbK+5BF5G04Ci+tyn96CM+cqJRWzcCFVgYGT7UeukxkMssPfPRv52xgMXL4v/KTQrgpy7VGiQqhVhD0nY/iEL4odc0gK/fvREqcYOU3dlDdTc8fRFSlO9Yw3yUK4xKm+0aB8QJW0Lex/rp6nRXkSewRqxr/0d3BYzA0D8kXzS/KtDAd4H4mtYhbCNzXJH37gappDa6qgwIDAQAB
    private final String GATEWAY_URL = "https://openapi.alipaydev.com/gateway.do";
    private final String FORMAT = "JSON";
    //签名方式
    private final String SIGN_TYPE = "RSA2";
    //支付宝异步通知路径,付款完毕后会异步调用本项目的方法,必须为公网地址
    private final String NOTIFY_URL = "http://localhost:8080/notifyUrl";
    //支付宝同步通知路径,也就是当付款完毕后跳转本项目的页面,可以不是公网地址
    private final String RETURN_URL = "http://localhost:8080/returnUrl";
    @Autowired
    private UserService userService;
    @Autowired
    private PurseService purseService;

    OrderCodeFactory orderCodeFactory;
    private Gson gson = new Gson();


    @RequestMapping(value = "/alipay", produces = "text/plain;charset=utf-8")
    public void alipay(HttpServletResponse httpResponse,HttpServletRequest req, Float money) throws IOException {
        /*RedirectAttributes attr,
        @ModelAttribute("bigOrder") BigOrder bigOrder,*/
        //实例化客户端,填入所需参数

        User user = (User) req.getSession().getAttribute("currentUser");

        /*BigOrder bigOrder= (BigOrder) session.getAttribute("bigOrder");*/
        AlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL, APP_ID, APP_PRIVATE_KEY, FORMAT, CHARSET, ALIPAY_PUBLIC_KEY, SIGN_TYPE);
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        //在公共参数中设置回跳和通知地址
        request.setReturnUrl(RETURN_URL);
        request.setNotifyUrl(NOTIFY_URL);
        String out_trade_no = orderCodeFactory.getRefundCode(Long.parseLong("1"));
        //获得付款金额，必填
        String total_amount = String.valueOf(money);
        //获得订单名称，必填
        String subject = "闲易交易";
        Date date = new Date();
        //获得商品描述，可空
        String body = "在" + date + "下了" + subject + "订单";
        // 该笔订单允许的最晚付款时间，逾期将关闭交易。
        // 取值范围：1m～15d。m-分钟，h-小时，d-天，1c-当天（1c-当天的情况下，无论交易何时创建，都在0点关闭）。 该参数数值不接受小数点， 如 1.5h，可转换为 90m。
        String timeout_express = "1m";
        request.setBizContent("{\"out_trade_no\":\"" + out_trade_no + "\","
                + "\"total_amount\":\"" + total_amount + "\","
                + "\"subject\":\"" + subject + "\","
                + "\"body\":\"" + body + "\","
                + "\"timeout_express\":\"" + timeout_express + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        String form = "";
        try {
            form = alipayClient.pageExecute(request).getBody(); // 调用SDK生成表单
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        httpResponse.setContentType("text/html;charset=" + CHARSET);
        httpResponse.getWriter().write(form);// 直接将完整的表单html输出到页面
        httpResponse.getWriter().flush();
        httpResponse.getWriter().close();
    }

    @RequestMapping(value = "/returnUrl", method = RequestMethod.GET)
    public String returnUrl(HttpServletRequest request)
            throws IOException, AlipayApiException {
        System.out.println("=================================同步回调=====================================");

        // 获取支付宝GET过来反馈信息
        Map<String, String> params = new HashMap<>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (String name : requestParams.keySet()) {
            String[] values = requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            // 乱码解决，这段代码在出现乱码时使用
            valueStr = new String(valueStr.getBytes("utf-8"), "utf-8");
            params.put(name, valueStr);
        }

//        System.out.println("---------------------"+params);//查看参数都有哪些
        boolean signVerified = AlipaySignature.rsaCheckV1(params, ALIPAY_PUBLIC_KEY, CHARSET, SIGN_TYPE); // 调用SDK验证签名
        //验证签名通过
        if (signVerified) {
            // 商户订单号
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");
            // 支付宝交易号
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");
            // 付款金额
            String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"), "UTF-8");

            System.out.println("商户订单号=" + out_trade_no);
            System.out.println("支付宝交易号=" + trade_no);
            System.out.println("付款金额=" + total_amount);
            User user = (User) request.getSession().getAttribute("currentUser");
            Float money= Float.valueOf(total_amount);
            Integer rst = purseService.rechargePurse(user.getId(), money);
            //支付成功，修复支付状态,这里自己改吧
            return "/user";//跳转付款成功页面
        } else {
            return "/no";//跳转付款失败页面
        }
    }

    @RequestMapping("notifyUrl")
    public String Notify(HttpServletRequest request) throws Exception {
        System.out.println("支付成功, 进入异步通知接口...");

        //获取支付宝POST过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (String name : requestParams.keySet()) {
            String[] values = requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }

        boolean signVerified = AlipaySignature.rsaCheckV1(params, ALIPAY_PUBLIC_KEY, CHARSET, SIGN_TYPE); //调用SDK验证签名


        if (signVerified) {//验证成功
            //商户订单号
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");

            //支付宝交易号
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");

            //交易状态
            String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"), "UTF-8");

            //付款金额
            String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"), "UTF-8");

            switch (trade_status) {
                case "TRADE_FINISHED":
                    //判断该笔订单是否在商户网站中已经做过处理
                    //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                    //如果有做过处理，不执行商户的业务程序

                    //注意： 尚自习的订单没有退款功能, 这个条件判断是进不来的, 所以此处不必写代码
                    //退款日期超过可退款期限后（如三个月可退款），支付宝系统发送该交易状态通知
                    break;
                case "TRADE_CLOSED":
                    System.out.println("超时未支付");
                    break;
                case "TRADE_SUCCESS":
                    //判断该笔订单是否在商户网站中已经做过处理
                    //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                    //如果有做过处理，不执行商户的业务程序
                    //修改支付状态
                    //增加支付完成时间

                    //注意：
                    //付款完成后，支付宝系统发送该交易状态通知

                    // 修改叮当状态，改为 支付成功，已付款; 同时新增支付流水
                    //修改叮当状态，改为 支付成功，已付款;


                    System.out.println("**********************支付成功(支付宝异步通知)********************");
                    System.out.println("* 订单号: " + out_trade_no);
                    System.out.println("* 支付宝交易号: " + trade_no);
                    System.out.println("* 实付金额: " + total_amount);
                    System.out.println("***************************************************************");
                    break;
            }

            System.out.println("支付成功...");

        } else {//验证失败
            System.out.println("支付, 验签失败...");
        }
        return "success";

    }


}
